//
//  NIMFeedProfileViewController.m
//  QianbaoIM
//
//  Created by iln on 14/8/18.
//  Copyright (c) 2014年 liu nian. All rights reserved.
//

#import "NIMFeedProfileViewController.h"
#import "NIMFeedTableViewCell.h"
#import "UIAlertView+NIMBlocks.h"
#import "NIMManager.h"
#import "NIMFeedUserCell.h"
#import "NIMFeedDetailShareCell.h"
#import "NIMFeedUserShareCell.h"
#import "NIMEditRemarkNameVC.h"
#import "NIMTNoDataView.h"
#import "NIMChatUIViewController.h"
#import "UIImage+NIMEllipse.h"
#import "SSIMThreadViewController.h"
#import "NIMContactsViewController.h"
#import "NIMPhotosWallPreviewViewController.h"
#import "NIMAddDescViewController.h"
#define kIdentifier_feed @"NIMFeedCell"
#define kIdentifier_plainText @"feedtext"
#define kIdentifier_pic @"feedimg"
#define kIdentifier_imgTxt @"feedimgtext"
#import "NIMActionSheet.h"

#define kPageSize 20

@interface NIMFeedProfileViewController ()<NSFetchedResultsControllerDelegate, FeedTableViewCellDelegate,NIMTNoDataViewDelegate>;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (strong, nonatomic) UIImageView *headBackgroundImageView;
@property (weak, nonatomic) IBOutlet UIButton *avatarBtn;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *signtureLabel;
@property (strong, nonatomic) UIButton *optionBtn;
@property (nonatomic, strong) UIView* optionBtnLine;
@property (nonatomic, weak) IBOutlet UIImageView* userIcon;
@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, strong) NIMTNoDataView         *qbm_viewNoData;
@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsControllerForVcard;
@property (nonatomic, strong) UIBarButtonItem* rightButtonItem;
@property (nonatomic, strong) UIBarButtonItem* rightEditProfileItem;

@property (nonatomic, strong) NSString* speadMoney;
@property (nonatomic, strong) NSString* firendsNum;
@property (nonatomic, strong) NSString* moreGameUrl;
@property (nonatomic, strong) NSString* totalCount;
@property (nonatomic, strong) NSString* gamesCount;
@property (nonatomic, strong) NSMutableArray* goodsList;
@property (nonatomic, strong) NSMutableArray* gamesList;
@property (nonatomic, strong) NSMutableDictionary* cellShowTextDataSource;
@property (nonatomic) BOOL isDeleteFriend;
@property (nonatomic, strong) NSString* lu;
@property (nonatomic) NSInteger offset,page;

// add by wxj 修改需求
@property (nonatomic, strong) UIImageView* headBgView;      //背景清晰图片
@property (nonatomic, strong) UIImageView* headBgBlurView;  //背景模糊图片
@property (nonatomic, strong) NSMutableArray* headBgUrlArr;    //背景清晰图片url数组
@property (nonatomic, strong) NSTimer* headBgTimer;         //背景切换定时器

@property (nonatomic, strong) UIImageView* avatarView;      //头像
@property (nonatomic, strong) UILabel* userNameLable;       //用户名
@property (nonatomic, strong) UIView * sexView;         //性别
@property (nonatomic, strong) UILabel* userSigntureLabel;   //签名
@property (nonatomic, strong) UIImageView* arrowImageView;  //向下箭头
@property (nonatomic, strong) NSMutableDictionary* userData;     //保存返回的用户数据。

@property (nonatomic,strong) UIImageView * sexImgView;
@property (nonatomic,strong) UILabel * ageLable;

@property (nonatomic, strong) UIImageView * locationImageView;     //保存返回的用户数据。
@property (nonatomic, strong) UILabel * locationLable;     //保存返回的用户数据。

@property (nonatomic, strong) UIAlertView* alert;          //提示。
@property (nonatomic, assign) BOOL userDataBack;          //提示。

@property (nonatomic,strong) NSMutableArray         *postDataSourceArray;
@property (nonatomic, strong) UIImageView *mySexImg;


@end

@implementation NIMFeedProfileViewController
{
    float headerViewH;
    int headBgIndex;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _postDataSourceArray = @[].mutableCopy;
    
    _userDataBack = NO;
    _userData = @{}.mutableCopy;
    _headBgTimer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(switchHeadBg:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_headBgTimer forMode:NSDefaultRunLoopMode];//手动加入到NSRunLoop中
    [_headBgTimer fire];
    headBgIndex = 0;
    
    _page = 0;
    //    _lu = @"";
    _headBgUrlArr = @[].mutableCopy;
    
    //创建视图
    [self creatView];
    //判断用户
    [self decideUser];
    //加载帖子列表
    [self refresh];
}

-(void)creatView{
    [_tableView.tableHeaderView setFrame:CGRectMake(0, 0, CGRectGetWidth(_tableView.frame), 265)];
    _headerView.clipsToBounds = NO;
    _headerView.backgroundColor = [UIColor whiteColor];
    [_headerView updateConstraintsIfNeeded];
    headerViewH = _headerView.frame.size.height;
    [[_headerView subviews]makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    
    _headBgView = [[UIImageView alloc]init];
    _headBgView.backgroundColor = [UIColor whiteColor];
    _headBgView.contentMode = UIViewContentModeScaleAspectFill;
    _headBgView.layer.masksToBounds = YES;
    [_headerView addSubview:_headBgView];
    [_headBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        //
        make.top.equalTo(@(0));
        make.left.equalTo(@(0));
        make.width.equalTo(_headerView.mas_width);
        make.height.equalTo(_headerView.mas_height);
    }];
    
    _headBgBlurView = [[UIImageView alloc]init];
    _headBgBlurView.backgroundColor = [UIColor darkGrayColor];
    _headBgBlurView.contentMode = UIViewContentModeScaleAspectFill;
    _headBgBlurView.alpha = 0;
    _headBgBlurView.layer.masksToBounds = YES;
    [_headerView addSubview:_headBgBlurView];
    _headBgBlurView.userInteractionEnabled = NO;
    //UITapGestureRecognizer *headBgTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headBgTap:)];
    //[_headBgBlurView addGestureRecognizer:headBgTap];
    
    [_headBgBlurView mas_makeConstraints:^(MASConstraintMaker *make) {
        //
        make.top.equalTo(@(0));
        make.left.equalTo(@(0));
        make.width.equalTo(_headerView.mas_width);
        make.height.equalTo(_headerView.mas_height);
    }];
    
    UIImage *defaultBgimage = IMGFROMBUNDLE_JPG(@"feedHome");
    [_headBgView setImage:defaultBgimage.copy];
    UIImage* img = [UIImage imageWithData:UIImageJPEGRepresentation(_headBgView.image, 0.4)];
    [_headBgBlurView setImage:[img.copy nim_uie_boxblurImageWithBlur:0.9]];
    _headBgBlurView.alpha = 1;
    
    _avatarView = [[UIImageView alloc]init];
    _avatarView.layer.borderColor = [UIColor whiteColor].CGColor;
    _avatarView.layer.borderWidth = 1;
    _avatarView.layer.cornerRadius = 80/2;
    _avatarView.layer.masksToBounds = YES;
    _avatarView.userInteractionEnabled = NO;
    //    _avatarView.userInteractionEnabled = YES;
    UITapGestureRecognizer *avatarTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(avatarTap:)];
    [_avatarView addGestureRecognizer:avatarTap];
    [_headerView addSubview:_avatarView];
    
    [_avatarView mas_makeConstraints:^(MASConstraintMaker *make) {
        //
        make.top.equalTo(@(60 + 20));
        make.centerX.equalTo(_headerView.mas_centerX);
        make.width.equalTo(@(80));
        make.height.equalTo(@(80));
    }];
    
    _userNameLable = [[UILabel alloc]init];
    _userNameLable.textColor = [UIColor whiteColor];
    [_headerView addSubview:_userNameLable];
    _userNameLable.font = [UIFont systemFontOfSize:16];
    _userNameLable.textAlignment= NSTextAlignmentCenter;
    
    [_userNameLable mas_makeConstraints:^(MASConstraintMaker *make) {
        //
        make.top.equalTo(_avatarView.mas_bottom).offset(10);
        make.centerX.equalTo(_headerView.mas_centerX).offset(-35/2);
        make.width.equalTo(@(20));
        make.height.equalTo(@(30));
    }];
    
    
    //性别背景
    _sexView = [[UIView alloc]init];
    _sexView.backgroundColor = [UIColor clearColor];
    _sexView.layer.cornerRadius = 3;
    _sexView.layer.masksToBounds = YES;
    [_headerView addSubview:_sexView];
    
    [_sexView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.userNameLable.mas_centerY);
        make.left.equalTo(_userNameLable.mas_right).offset(5);
        make.width.equalTo(@(40));
        make.height.equalTo(@(12));
    }];
    
    
    _sexImgView = [[UIImageView alloc]init];
    _sexImgView.contentMode = UIViewContentModeScaleAspectFit;
    [_sexView addSubview:_sexImgView];
    
    [_sexImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.sexView.mas_top).offset(1);;
        make.bottom.equalTo(self.sexView.mas_bottom).offset(-1);
        make.left.equalTo(self.sexView.mas_left).offset(1);
        make.width.equalTo(@(14));
    }];
    
    _ageLable = [[UILabel alloc]init];
    _ageLable.textColor = [UIColor whiteColor];
    _ageLable.textAlignment = NSTextAlignmentCenter;
    _ageLable.font = [UIFont systemFontOfSize:11];
    [_sexView addSubview:_ageLable];
    
    [_ageLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.sexImgView.mas_top);
        make.bottom.equalTo(self.sexImgView.mas_bottom);
        make.left.equalTo(self.sexImgView.mas_right).offset(-1);
        make.right.equalTo(self.sexView.mas_right).offset(-1);
    }];
    
    _userSigntureLabel = [[UILabel alloc]init];
    _userSigntureLabel.textColor = [UIColor whiteColor];
    _userSigntureLabel.textAlignment= NSTextAlignmentCenter;
    _userSigntureLabel.font = [UIFont systemFontOfSize:13];
    _userSigntureLabel.numberOfLines = 0;
    _userSigntureLabel.text = @"暂无简介";
    [_headerView addSubview:_userSigntureLabel];
    [_userSigntureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_userNameLable.mas_bottom).offset(3);
        make.centerX.equalTo(_headerView.mas_centerX);
        make.width.equalTo(@(300));
        make.height.equalTo(@(40));
    }];
    
    
    _arrowImageView = [[UIImageView alloc]init];
    _arrowImageView.image = IMG2XFROMBUNDLE(@"btn_open");
    _arrowImageView.contentMode = UIViewContentModeCenter;
    UITapGestureRecognizer * headBgTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headBgTapopen:)];
    _arrowImageView.userInteractionEnabled = YES;
    [_arrowImageView addGestureRecognizer:headBgTap];
    
    [_headerView addSubview:_arrowImageView];
    [_arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_headerView.mas_bottom).offset(-37);
        make.centerX.equalTo(_userSigntureLabel.mas_centerX);
        make.width.equalTo(@(35));
        make.height.equalTo(@(35));
    }];
    
    _locationImageView = [[UIImageView alloc]init];
    [_headerView addSubview:_locationImageView];
    [_locationImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_headerView.mas_bottom).offset(-13);
        make.left.equalTo(@(5));
        make.width.equalTo(@(12));
        make.height.equalTo(@(12));
    }];
    
    _locationLable = [[UILabel alloc]init];
    _locationLable.textColor = COLOR_RGBA(224, 224, 224, 1);
    _locationLable.font = [UIFont systemFontOfSize:13];
    [_headerView addSubview:_locationLable];
    
    _locationLable.text = @"无法获取位置";
    [_locationLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_headerView.mas_bottom).offset(-11);
        make.left.equalTo(_locationImageView.mas_right).offset(5);
        make.width.equalTo(@(200));
        make.height.equalTo(@(15));
    }];
    
    [_tableView registerClass:[NIMFeedUserCell class] forCellReuseIdentifier:kNIMFeedUserCell];
    [_tableView registerClass:[NIMFeedUserShareCell class] forCellReuseIdentifier:kNIMFeedUserShareCell];
    
    _userIcon.layer.cornerRadius = 35;
    _userIcon.layer.masksToBounds = YES;
    [_userIcon sd_setImageWithURL:[NSURL URLWithString:_vcardEntity.avatar] placeholderImage:__IMAGE_PLACEHODER_USERICON__];
    
    
    _userDataBack = NO;
    if(_tableView.contentOffset.y>64){
        [self setNavigationBarTransparent:2];
    }else{
        [self setNavigationBarTransparent:1];
    }
    
    _optionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _optionBtn.backgroundColor = [UIColor whiteColor];
    [_optionBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_optionBtn addTarget:self action:@selector(friendBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //    _optionBtn.userInteractionEnabled = NO;
    
    [self.view addSubview:_optionBtn];
    if (_optionBtn.superview !=nil) {
        [_optionBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.offset(0);
            make.trailing.offset(0);
            make.bottom.offset(0);
            make.height.offset(59);
        }];
    }
    [_avatarView sd_setImageWithURL:[NSURL URLWithString:_vcardEntity.avatar] placeholderImage:__IMAGE_PLACEHODER_USERICON__];
}

-(void)decideUser{
    //判断用户
    if (_userid) {
        _searchContent = [NSString stringWithFormat:@"%lld",_userid];
        VcardEntity * vcard = [VcardEntity instancetypeFindUserid:_userid];
        if (vcard) {
            _vcardEntity = vcard;
            [self getuserinfo];
        }else{
            [[NIMUserOperationBox sharedInstance] sendUserInfo:_searchContent type:_userid];
        }
    }else{
        NSString * searchName;
        
        if ([SSIMSpUtil isPhoneNum:_searchContent]) {
            searchName = @"mobile";
        }else if ([SSIMSpUtil isTypeNumber:_searchContent]){
            searchName = @"userid";
        }else{
            searchName = @"userName";
        }
        
        VcardEntity * vcard = [VcardEntity NIM_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"%@ = %@",searchName,_searchContent]];
        
        if (vcard) {
            _vcardEntity = vcard;
            [self getuserinfo];
        }
    }
    [[NIMUserOperationBox sharedInstance] sendUserInfo:_searchContent type:Search_PeedView];
}

-(void)getuserinfo{
    
    _fdlist = [FDListEntity NIM_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"fdOwnId = %lld and fdPeerId = %lld ",OWNERID,_vcardEntity.userid]];
    if (self.groupid!=0) {
        GroupList *groupList = [GroupList instancetypeFindGroupId:self.groupid];
        if (groupList) {
            GMember *member = [GMember instancetypeFindUserid:self.userid group:groupList];
            
            BOOL isSet = !IsStrEmpty(_fdlist.fdRemarkName) && ![member.showName isEqualToString:_fdlist.fdRemarkName];
            if (isSet) {
                member.showName = _fdlist.fdRemarkName;
                member.fullLitter = [PinYinManager getFullPinyinString:_fdlist.fdRemarkName];
                if (![member.fLitter isEqualToString:[PinYinManager getFirstLetter:_fdlist.fdRemarkName]]) {
                    member.fLitter = [PinYinManager getFirstLetter:_fdlist.fdRemarkName];
                }
                [[NIMCoreDataManager currentCoreDataManager] saveDataToDisk];
            }
        }
    }
    
    if ([_fdlist defaultName]) {
        _nameLabel.text = [_fdlist defaultName];
        _userNameLable.text = [_fdlist defaultName];
        
    }else{
        _nameLabel.text = [_vcardEntity defaultName];
        _userNameLable.text = [_vcardEntity defaultName];
    }
    _nameLabel.textAlignment= NSTextAlignmentCenter;
    _userNameLable.textAlignment= NSTextAlignmentCenter;
    
    [_avatarView sd_setImageWithURL:[NSURL URLWithString:_vcardEntity.avatar] placeholderImage:__IMAGE_PLACEHODER_USERICON__];
    [self configHeaderViewIndex:0];
    [self updateHeadViewData:_userData];
    [_tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recvNC_USERINFO_RQ_ForPeedView:) name:NC_USERINFO_RQ_ForPeedView object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recvNC_FRIEND_DEL_RQ:) name:NC_FRIEND_DEL_RQ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recvFEEDPROFILE:) name:@"FEEDPROFILE" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recvNC_ADD_BLACK_RQ:) name:NC_ADD_BLACK_RQ object:nil];
    
    [self qb_setNavStyleTheme:THEME_COLOR_WHITHE_D];
}



#pragma mark 11.7
// 更新 年龄性别样式
- (void)updateHeadViewData:(NSMutableDictionary *)userData{
    float wid = [[UIScreen mainScreen] bounds].size.width;
    
    NSString *name = @"";
    
    _fdlist = [FDListEntity NIM_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"fdOwnId = %lld and fdPeerId = %lld ",OWNERID,_vcardEntity.userid]];
    if ([_fdlist defaultName]) {
        name = [_fdlist defaultName];
    }else{
        name = [_vcardEntity defaultName];
    }
    
    CGSize sizeForUserName = [name boundingRectWithSize:CGSizeMake(200, 12) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:_userNameLable.font} context:nil].size;
    _userNameLable.text = name;
    float userNameOffset = 0;
    if (sizeForUserName.width > 150) {
        userNameOffset = -35/2;
    }
    [_userNameLable mas_updateConstraints:^(MASConstraintMaker *make) {
        //
        make.top.equalTo(_avatarView.mas_bottom).offset(10);
        make.centerX.equalTo(_headerView.mas_centerX).offset(userNameOffset);
        make.width.equalTo(@(sizeForUserName.width + 7));
        make.height.equalTo(@(20));
    }];
    
    NSString *signature = _vcardEntity.signature;
    if(signature && signature!= NULL && ![signature isEqualToString:@"null"]){
        
        [_userSigntureLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_userNameLable.mas_bottom).offset(3);
            make.centerX.equalTo(_headerView.mas_centerX);
            make.width.equalTo(@300);
            make.height.equalTo(@(20));
        }];
        if (!IsStrEmpty(_vcardEntity.signature)) {
            _userSigntureLabel.text = signature;
        }else{
            _userSigntureLabel.text = @"暂无简介";
        }
    }
    
    
    //更新性别
    if([_vcardEntity.sex isEqualToString:USER_SEX_FEMALE])
    {
        [_sexView setBackgroundColor:COLOR_RGBA(241, 46, 90, 1)];
        [_sexImgView setImage:IMGFROMBUNDLE(@"icon_girl.png")];
    }else
    {
        [_sexView setBackgroundColor:COLOR_RGBA(19, 149, 255, 1)];
        [_sexImgView setImage:IMGFROMBUNDLE(@"icon_boy.png")];
    }
    
    //更新年龄
    NSString * userAge = [NSString stringWithFormat:@"%d",_vcardEntity.age];
    
    if([userAge isEqualToString:@""] || userAge == nil || [userAge isEqualToString: @"0"] || IsStrEmpty(userAge) || userAge.length == 0)
    {
        _ageLable.hidden = YES;
        
        [_sexView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.userNameLable.mas_centerY);
            make.left.equalTo(_userNameLable.mas_right).offset(5);
            make.width.equalTo(@(16));
            make.height.equalTo(@(12));
        }];
    }
    else
    {
        _ageLable.text = userAge;
        
        if (userAge.length == 1) {
            [_sexView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(self.userNameLable.mas_centerY);
                make.left.equalTo(_userNameLable.mas_right).offset(5);
                make.width.equalTo(@(24));
                make.height.equalTo(@(12));
            }];
        }else if (userAge.length == 2){
            [_sexView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(self.userNameLable.mas_centerY);
                make.left.equalTo(_userNameLable.mas_right).offset(5);
                make.width.equalTo(@(30));
                make.height.equalTo(@(12));
            }];
        }
    }
    
    
    NSString *provincesStr = _vcardEntity.city;
    NSString *cityStr = _vcardEntity.locationPro;
    if ((provincesStr && ![provincesStr isEqualToString:@""]) && (cityStr && ![cityStr isEqualToString:@""])) {
        //        _locationLable.hidden = NO;
        _locationImageView.image = IMG2XFROMBUNDLE(@"icon_city");
        _locationLable.text = [NSString stringWithFormat:@"%@ %@",cityStr,provincesStr];
    }else{
        _locationImageView.image = IMG2XFROMBUNDLE(@"icon_city");
        //        _locationLable.hidden = YES;
    }
    
    [_locationLable mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_headerView.mas_bottom).offset(-11);
        make.left.equalTo(_locationImageView.mas_right).offset(5);
        make.width.equalTo(@(200));
        make.height.equalTo(@(15));
    }];
    [_locationImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_headerView.mas_bottom).offset(-14);
        make.left.equalTo(@(15));
        make.width.equalTo(@(12));
        make.height.equalTo(@(12));
    }];
    [self.view setNeedsUpdateConstraints];
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];
}
- (void)requestPostsWithActionType:(NSString*)actioneType{
    //请求 数据列表
    //    NSString *minPostId = @"0";
    if([actioneType isEqualToString:@"loadMore"]){
        if (self.postDataSourceArray.count > 0) {
            // PostsModel *postModel = [self.postDataSourceArray lastObject];
            //minPostId = postModel.postid;
        }
    }
}

#pragma mark fetch
- (void)refresh{
    //    _lu = @"";
    [self requestPostsWithActionType:@"refresh"];
    [self requestBgList:[NSString stringWithFormat:@"%d",(int)_userid]];
}

- (void)loadMore
{
    // 计算page
    [self requestPostsWithActionType:@"loadMore"];
}
-(void)showNodataView:(NSString*)string atView:(UIView*)view
{
    [_tableView addSubview:_qbm_viewNoData];
    _qbm_viewNoData.labError.text = string;
    
    CGFloat height = 0;
    if(_qbm_viewNoData.userIMG)
    {
        height = 150;
    }
    else
    {
        height = 50;
    }
    
    float systemName = [[[UIDevice currentDevice]systemVersion]floatValue];
    if(systemName >= 8.0){
        [_qbm_viewNoData mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_tableView.mas_centerX).offset(CGPointZero.x);
            make.centerY.equalTo(_tableView.mas_centerY).offset(CGPointZero.y+50);
            make.width.equalTo(@(150));
            make.height.equalTo(@(height));
        }];
    }else{
        CGPoint p=_qbm_viewNoData.center;
        p.x = _tableView.center.x;
        p.y = _tableView.center.y+120;
        _qbm_viewNoData.center = p;
    }
    
    
}
- (void)setTableViewDataSource{
    [_tableView reloadData];
    
}
#pragma mark actions
- (void)refreshViewControlEventValueChanged{
    [self refresh];
}
- (IBAction)friendBtnClick:(id)sender{
    
    NIMFriendshipType friendshipType;
    
    if (_vcardEntity) {
        FDListEntity * fdlist = [FDListEntity NIM_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"fdOwnId = %lld and fdPeerId = %lld ",OWNERID,_vcardEntity.userid]];
        friendshipType = fdlist.fdFriendShip;
    }
    
    if (_vcardEntity.userid == OWNERID) {
        friendshipType = FriendShip_IsMe;
    }
    
    switch (friendshipType) {
        case FriendShip_NotFriend:
        case FriendShip_Ask_Peer:
        case FriendShip_Ask_Me:
        case FriendShip_Outlast:
        case FriendShip_MobileRecommend:
        {
            
            NIMAddDescViewController *descViewController = [[NIMAddDescViewController alloc] init];
            descViewController.userId = _userid;
            descViewController.addSourceType = _feedSourceType;
            UINavigationController *presNavigation = [[UINavigationController alloc] initWithRootViewController: descViewController];
            
            descViewController.addBackRefesh = ^(){
                DBLog(@"返回刷新");
                [self getuserinfo];
            };
            
            //            hud.userInteractionEnabled= NO;
            
            
            [self presentViewController:presNavigation animated:YES completion:nil];
            
            
            break;
        }case FriendShip_IsMe:{
            
            
            break;
        }
        case FriendShip_Friended:
        case FriendShip_Consent_Peer:
        case FriendShip_UnilateralFriended:
        {
            
            //            [QBClick event:kUMEventId_3021];
            NIMChatUIViewController *chatVC = [[NIMChatUIViewController alloc] init];
            [chatVC setThread:[NSString stringWithFormat:@"4:%lld:%lld",OWNERID,_vcardEntity.userid]];
            [chatVC setActualThread:[NSString stringWithFormat:@"4:%lld:%lld",OWNERID,_vcardEntity.userid]];
            chatVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:chatVC animated:YES];
            
            
            break;
        }
        default:
            break;
    }
}
#pragma mark config
- (void)configFriendshipBtn{
    
    UIImage *image = [IMG2XFROMBUNDLE(@"bg_cha_2.png") resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [_optionBtn setBackgroundImage:nil forState:UIControlStateNormal];
    [_optionBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    NSString *title = @"加为好友";
    
    _vcardEntity = [VcardEntity instancetypeFindUserid:_userid];
    
    _optionBtnLine.backgroundColor = [UIColor clearColor];
    
    NIMFriendshipType friendshipType;
    
    if (_vcardEntity) {
        FDListEntity * fdlist = [FDListEntity NIM_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"fdOwnId = %lld and fdPeerId = %lld",OWNERID,_vcardEntity.userid]];
        friendshipType = fdlist.fdFriendShip;
    }
    
    if (_vcardEntity.userid == OWNERID) {
        friendshipType = FriendShip_IsMe;
    }
    
    //    DBLog(@"friendship:%ld",(long)friendshipType);
    
    switch (friendshipType) {
        case FriendShip_NotFriend:
        case FriendShip_Ask_Peer:
        case FriendShip_Ask_Me:
        case FriendShip_Outlast:
        case FriendShip_MobileRecommend:
        {
            title = @"加为好友";
            [_optionBtn setBackgroundImage:image forState:UIControlStateNormal];
            [self.navigationItem setRightBarButtonItem:nil];
            
            self.rightButton.hidden = YES;
            _rightButton.userInteractionEnabled = NO;
        }
            break;
        case FriendShip_IsMe:
        {
            _optionBtn.hidden = YES;
            self.rightButton.hidden = YES;
            _rightButton.userInteractionEnabled = NO;
            
        }
            break;
        case FriendShip_Friended:
        case FriendShip_Consent_Peer:
        case FriendShip_UnilateralFriended:
        {
            self.rightButton.hidden = NO;
            _rightButton.userInteractionEnabled = YES;
            
            title = @"发消息";
            //            [self setNavigationBarTransparent:1];
            
            [_optionBtn setBackgroundColor:[UIColor whiteColor]];
            [_optionBtn setTitleColor:[UIColor colorWithRed:19/255.0 green:86/255.0 blue:215/255.0 alpha:1] forState:UIControlStateNormal];
            
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:IMG2XFROMBUNDLE(@"icon_channel_more") style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction:)];
            [self qb_showRightButtonWithImg:IMG2XFROMBUNDLE(@"icon_channel_more")];
            ;
            self.optionBtnLine.backgroundColor = __COLOR_D5D5D5__;
        }
            break;
            
        default:
            break;
    }
    
    [_optionBtn setTitle:title forState:UIControlStateNormal];
}
- (void)configHeaderViewIndex:(int)index{
    
    headBgIndex = index;
    if (_headBgUrlArr.count) {
        NSURL *imageUrl = [NSURL URLWithString:[_headBgUrlArr objectAtIndex:index]];
        [_headBgView sd_setImageWithURL:imageUrl placeholderImage:IMGFROMBUNDLE_JPG(@"feedHome") completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [_headBgView setImage:image.copy];
            UIImage* img = [UIImage imageWithData:UIImageJPEGRepresentation(_headBgView.image, 0.4)];
            [_headBgBlurView setImage:[img.copy nim_uie_boxblurImageWithBlur:0.9]];
            _headBgBlurView.alpha = 1;
        }];
    }else{
        UIImage *defaultBgimage = IMGFROMBUNDLE_JPG(@"feedHome");
        [_headBgView setImage:defaultBgimage.copy];
        UIImage* img = [UIImage imageWithData:UIImageJPEGRepresentation(_headBgView.image, 0.4)];
        [_headBgBlurView setImage:[img.copy nim_uie_boxblurImageWithBlur:0.9]];
        _headBgBlurView.alpha = 1;
    }
    [self configFriendshipBtn];
}
#pragma mark -背景列表
- (void)requestBgList:(NSString *)userid{
    //请求 数据列表
    //    NSMutableDictionary *param = @{@"userid":userid}.mutableCopy;
    // 加载帖子数据
}

- (void)switchHeadBg:(NSTimer *)timer{
    if (_headBgUrlArr.count<2) {
        return;
    }else{
        headBgIndex = headBgIndex + 1;
        int count = (int)_headBgUrlArr.count;
        headBgIndex = headBgIndex%count;
        [_headBgView sd_setImageWithURL:[NSURL URLWithString:[_headBgUrlArr objectAtIndex:headBgIndex]]
                       placeholderImage:IMGFROMBUNDLE_JPG(@"feedHome")
                              completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                                  [_headBgView setImage:image];
                                  UIImage* img = [UIImage imageWithData:UIImageJPEGRepresentation(_headBgView.image, 0.4)];
                                  [_headBgBlurView setImage:[img.copy nim_uie_boxblurImageWithBlur:0.9]];
                                  _headBgBlurView.alpha = 1;
                              }];
    }
}
#pragma mark - 点击头像，背景11.7

- (void)avatarTap:(UITapGestureRecognizer *)tap{
    //    UIImageView *avatarView = (UIImageView *)tap.view;
    
    NSString *avatarUrlStr = nil;
    NSString *avatarThumbUrlStr = nil;
    
    
    if (_vcardEntity.avatar) {
        avatarThumbUrlStr = _vcardEntity.avatar;
        avatarUrlStr = avatarThumbUrlStr;
    }
    if (_vcardEntity.avatar300) {
        avatarUrlStr = _vcardEntity.avatar300;
    }
    NIMPhotosWallPreviewViewController *ct = [[NIMPhotosWallPreviewViewController alloc]init];
    ct.placeHoderImage = __IMAGE_PLACEHODER_USERICON__;
    ct.titleText = @"头像";
    ct.rightBtText = _ScanNoneType;
    ct.showBack = YES;
    ct.hidePageCt = TRUE;
    ct.selectedIndex = 0;
    
    if(avatarThumbUrlStr){
        ct.thumbImageUrls = @[avatarThumbUrlStr].mutableCopy;
    }
    if (avatarUrlStr) {
        ct.imagesUrls = @[avatarUrlStr].mutableCopy;
    }
    
    if (ct.imagesUrls.count == 0) {
        ct.localImages = @[__IMAGE_PLACEHODER_USERICON__].mutableCopy;
    }
    if (ct.thumbImageUrls.count == 0 ) {
        ct.localImages = @[__IMAGE_PLACEHODER_USERICON__].mutableCopy;
    }
    ct.delegate = self;
    [self.navigationController pushViewController:ct animated:YES];
}

- (void)headBgTapopen:(UITapGestureRecognizer *)tap{
    
    //if (_userData.allKeys.count == 0) {
    //        [_view showTipsView:@"网络出错"];
    //  return;
    //}
    
    // 告诉_view约束需要更新
    [self.view setNeedsUpdateConstraints];
    // 调用此方法告诉_view检测是否需要更新约束，若需要则更新，下面添加动画效果才起作用
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];
    [_headBgTimer invalidate];
    _qbm_viewNoData.alpha = 0;
    _avatarView.alpha = 0;
    _userNameLable.alpha = 0;
    _userSigntureLabel.alpha = 0;
    _sexView.alpha = 0;
    _arrowImageView.alpha = 0;
    _headBgBlurView.alpha = 0;
    _locationImageView.alpha = 0;
    _locationLable.alpha = 0;
    if(_headBgView.image.size.width >= _headBgView.image.size.height){
        _headBgView.contentMode = UIViewContentModeScaleAspectFit;
        _headBgBlurView.contentMode = UIViewContentModeScaleAspectFit;
    }else{
        _headBgView.contentMode = UIViewContentModeScaleAspectFill;
        _headBgBlurView.contentMode = UIViewContentModeScaleAspectFill;
    }
    
    
    NSMutableArray * thumbImageUrls  =@[].mutableCopy;
    for (NSString *imageUrl in _headBgUrlArr) {
        [thumbImageUrls addObject:[NSString stringWithFormat:@"%@/%@",imageUrl,@"200"]];
    }
    NIMPhotosWallPreviewViewController *ct = [[NIMPhotosWallPreviewViewController alloc]init];
    if(_userNameLable.text){
        NSString *text = _userNameLable.text;
        int wordLength = 0;
        for(int i=0; i< [text length];i++){
            int a = [text characterAtIndex:i];
            if( a > 0x4e00 && a < 0x9fff){
                wordLength = wordLength + 2;
            }else{
                wordLength = wordLength + 1;
            }
            if (wordLength >= 10) {
                text = [text substringWithRange:NSMakeRange(0,i+1)];
                text = [NSString stringWithFormat:@"%@...",text];
                break;
            }
        }
        
        ct.titleText = [NSString stringWithFormat:@"%@%@",text,@"照片墙"];
    }
    ct.rightBtType = _ScanNoneType;
    if (_userid == OWNERID) {
        ct.rightBtType = _ScanEditType;
        ct.rightBtText = @"编辑";
    }
    ct.showBack = NO;
    ct.selectedIndex = headBgIndex;
    ct.imagesUrls = _headBgUrlArr;
    ct.thumbImageUrls = thumbImageUrls;
    ct.delegate = self;
    if (!thumbImageUrls.count) {
        //ct.localImages = @[IMGFROMBUNDLE_JPG(@"feedHome")].mutableCopy;
    }
    ct.localImages = @[IMGFROMBUNDLE_JPG(@"feedHome")].mutableCopy;
    
    [UIView animateWithDuration:0.49f animations:^{
        [_headerView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top).offset(0);
            make.left.equalTo(@(0));
            make.width.equalTo(self.view.mas_width);
            make.bottom.equalTo(self.view.mas_bottom).offset(0);
        }];
        [self.view layoutIfNeeded];
    }completion:^(BOOL finished) {
        // 去掉加载第一张的进度条。
        [self performSelector:@selector(pushWithDalay:) withObject:ct afterDelay:0.01];
    }];
    
    
}
- (void)pushWithDalay:(UIViewController *)ct{
    [self.navigationController pushViewController:ct animated:NO];
    
}

- (void)resetBgImageWithIndex:(int)index imagesUrls:(NSMutableArray *)imageUrls{
    //返回更新数据 （编辑图片时候增删改）
    _headBgUrlArr = imageUrls;
    [self configHeaderViewIndex:index];
    
    [self headerAnimateClosed];
}

- (void)headerAnimateClosed{
    // 告诉_view约束需要更新
    [self.view setNeedsUpdateConstraints];
    // 调用此方法告诉_view检测是否需要更新约束，若需要则更新，下面添加动画效果才起作用
    [self.view updateConstraintsIfNeeded];
    [self.view layoutIfNeeded];
    if(_headBgView.image.size.width <= _headBgView.image.size.height){
        _headBgView.contentMode = UIViewContentModeScaleToFill;
        _headBgBlurView.contentMode = UIViewContentModeScaleToFill;
    }
    
    [UIView animateWithDuration:0.5f
                     animations:^{
                         _headBgBlurView.alpha = 1;
                         [_headerView mas_remakeConstraints:^(MASConstraintMaker *make) {
                             make.top.equalTo(self.view.mas_top).offset(0);
                             make.left.equalTo(@(0));
                             make.width.equalTo(self.view.mas_width);
                             make.height.equalTo(@(headerViewH));
                         }];
                         [self.view layoutIfNeeded];
                     }completion:^(BOOL finished) {
                         [_headerView mas_remakeConstraints:^(MASConstraintMaker *make) {
                             make.top.equalTo(_headerView.superview.mas_top).offset(0);
                             make.left.equalTo(@(0));
                             make.width.equalTo(self.view.mas_width);
                             make.height.equalTo(@(headerViewH));
                         }];
                         
                         
                         _headBgView.contentMode = UIViewContentModeScaleAspectFill;
                         _headBgBlurView.contentMode = UIViewContentModeScaleAspectFill;
                         
                         _qbm_viewNoData.alpha = 1;
                         _avatarView.alpha = 1;
                         _userNameLable.alpha = 1;
                         _userSigntureLabel.alpha = 1;
                         _sexView.alpha = 1;
                         _arrowImageView.alpha = 1;
                         _locationImageView.alpha = 1;
                         _locationLable.alpha = 1;
                         if (!_headBgTimer.isValid) {
                             [self performSelector:@selector(reloadTimer) withObject:nil afterDelay:5];
                         }
                     }];
}

- (void)reloadTimer{
    _headBgTimer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(switchHeadBg:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_headBgTimer forMode:NSDefaultRunLoopMode];//手动加入到NSRunLoop中
    [_headBgTimer fire];
}

- (void)qb_rightButtonAction{
    FDListEntity * fdlist = [FDListEntity NIM_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"fdOwnId = %lld  and fdPeerId = %lld and (fdFriendShip = %d || fdFriendShip = %d)",OWNERID,_vcardEntity.userid,FriendShip_Friended,FriendShip_UnilateralFriended]];
    
    NSString * delStr = @"";
    if (fdlist) {
        delStr = [fdlist defaultName];
    }else{
        delStr = [_vcardEntity defaultName];
    }
    
    NSString * blackStr = @"";
    NSString * blackSure = @"";
    NSString * notCall = @"";
    NIMFDBlackShipType blacktype;
    
    if (fdlist.fdBlackShip == FD_BLACK_NOT_BLACK || fdlist.fdBlackShip == FD_BLACK_PASSIVE_BLACK) {
        blackStr = @"加入黑名单";
        blackSure = @"确认加入";
        blacktype = 1;
        notCall = @"你将不再收到对方的消息";
    }else if (fdlist.fdBlackShip == FD_BLACK_MUTUAL_BLACK || fdlist.fdBlackShip == FD_BLACK_ACTIVE_BLACK){
        blackStr = @"移出黑名单";
        blackSure = @"确认移出";
        notCall = @"";
        blacktype = 0;
    }
    
    NIMActionSheet * actionSheet = [[NIMActionSheet alloc] initWithCancelStr:@"取消" otherButtonTitles:@[@"修改备注",@"删除好友",blackStr] AttachTitle:@""];
    
    //            [action ChangeTitleColor:[UIColor redColor] AndIndex:1];
    
    [actionSheet ButtonIndex:^(NSInteger Buttonindex) {
        
        
        if (Buttonindex == 1) {
            
            NIMEditRemarkNameVC* remark = [[NIMEditRemarkNameVC alloc] initWithNibName:@"NIMEditRemarkNameVC" bundle:[SSIMBundleTool getBundle]];
            remark.userId = self.userid;
            if (_fdlist) {
                if ([_fdlist defaultName]) {
                    remark.remarkName = [_fdlist defaultName];
                }
            }
            remark.backRefesh = ^(){
                DBLog(@"返回刷新");
                [self getuserinfo];
            };
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATETABLE" object:nil];
            [self.navigationController pushViewController:remark animated:YES];
            
        }else if (Buttonindex == 2) {
            
            NSString *str =[NSString stringWithFormat:@"将联系人“%@”删除\n同时删除与他的聊天记录",delStr];
            
            NIMActionSheet * actionSheet = [[NIMActionSheet alloc] initWithCancelStr:@"取消" otherButtonTitles:@[@"确认删除"] AttachTitle:str];
            
            //            [action ChangeTitleColor:[UIColor redColor] AndIndex:1];
            
            [actionSheet ButtonIndex:^(NSInteger Buttonindex) {
                
                if (Buttonindex == 1) {
                    
                                        dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
                                        });
                    
                    [[NIMFriendManager sharedInstance] sendFriendDelRQ:_vcardEntity.userid];
                }
            }];
            
        }else if (Buttonindex == 3){
            NSString *str =[NSString stringWithFormat:@"将联系人“%@”%@。%@",delStr,blackStr,notCall];
            NIMActionSheet * actionSheet = [[NIMActionSheet alloc] initWithCancelStr:@"取消" otherButtonTitles:@[blackSure] AttachTitle:str];
            [actionSheet ButtonIndex:^(NSInteger Buttonindex) {
                
                if (Buttonindex == 1) {
                                        dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
                                        });
                    [[NIMFriendManager sharedInstance] addBlackListRQ:_vcardEntity.userid blackType:blacktype];
                }
            }];
        }
    }];
}

-(void)recvNC_USERINFO_RQ_ForPeedView:(NSNotification *)noti{
    
    dispatch_async(dispatch_get_main_queue(), ^{
//        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
        
        if ([noti.userInfo[@"success"] intValue]) {
            //            [MBTip showTipsView:@"查找成功" atView:self.view];
            _userid = [noti.userInfo[@"userId"] intValue];
            VcardEntity * vcard = [VcardEntity instancetypeFindUserid:_userid];
            _vcardEntity = vcard;
            [self getuserinfo];
        }else{
            //            [MBTip showTipsView:noti.userInfo[@"error"]  atView:self.view];
        }
    });
}

-(void)recvNC_FRIEND_DEL_RQ:(NSNotification *)noti{
    
    id object = noti.object;
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
        if (object) {
            if ([object isKindOfClass:[QBNCParam class]]) {
                QBNCParam *param = object;
                [MBTip showTipsView:param.p_string atView:self.view];
            }else{
                [MBTip showTipsView:@"删除成功" atView:self.view];
                
                UIViewController *target=nil;
                for (UIViewController *vc in self.navigationController.viewControllers) {
                    if ([vc isKindOfClass:[SSIMThreadViewController class]]) {
                        target=vc;
                    }else if ([vc isKindOfClass:[NIMContactsViewController class]]){
                        target=vc;
                    }
                }
                if (target) {
                    [self.navigationController popToViewController:target animated:NO];
                }else{
                    [self.navigationController popViewControllerAnimated:NO];
                }
            }
        }else{
            UIAlertController * netAlert = [UIAlertController alertControllerWithTitle:@"网络异常" message:@"请检查当前网络设置" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * nAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [netAlert addAction:nAction];
            [self presentViewController:netAlert animated:YES completion:^{
            }];
            //            [MBTip showError:@"删除失败" toView:self.view];
        }
        [self.tableView reloadData];
    });
}


-(void)recvNC_ADD_BLACK_RQ:(NSNotification *)noti{
    
    id object = noti.object;
    NSString * type = object;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
        if (object) {
            if ([object isKindOfClass:[QBNCParam class]]) {
                QBNCParam *param = object;
                [MBTip showError:param.p_string toView:self.view.window];
                
            }else{
                //                [self.navigationController popViewControllerAnimated:YES];
                
                if ([type isEqualToString:@"0"]) {
                    [MBTip showError:@"移出黑名单成功" toView:self.view.window];
                }else if ([type isEqualToString:@"1"]){
                    [MBTip showError:@"添加黑名单成功" toView:self.view.window];
                }
            }
        }else{
            UIAlertController * netAlert = [UIAlertController alertControllerWithTitle:@"网络异常" message:@"请检查当前网络设置" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * nAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [netAlert addAction:nAction];
            [self presentViewController:netAlert animated:YES completion:^{
            }];
        }
        [self.tableView reloadData];
    });
}

-(void)recvFEEDPROFILE:(NSNotification *)noti{
    NSDictionary * dict = noti.object;
    
    if (_userid == [[dict objectForKey:@"userId"] intValue]) {
        if (![[dict objectForKey:@"fdResult"] intValue]) {
            [self configFriendshipBtn];
        }
    }
}

//-(void)recvNC_SERVER_FRIEND_ADD_RQ:(NSNotification *)noti{
//    NSDictionary * dict = noti.object;
//    
//    if (_userid == [[dict objectForKey:@"userId"] intValue]) {
//        if (![[dict objectForKey:@"fdResult"] intValue]) {
//            [self configFriendshipBtn];
//        }
//    }
//}



-(void)saveVcard
{
    NSManagedObjectContext *privateContext = [[NIMCoreDataManager currentCoreDataManager] privateObjectContext];
    [privateContext performBlockAndWait:^{
        VcardEntity* vcard = [VcardEntity NIM_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"userid=%f",_userid]];
        vcard = _vcardEntity;
        [privateContext MR_saveToPersistentStoreAndWait];
    }];
    
}
#pragma mark scroll view delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(scrollView.contentOffset.y<64)
    {
        [self setNavigationBarTransparent:1];
    }
    else{
        [self setNavigationBarTransparent:2];
    }
    if (scrollView.contentOffset.y < -64) {
        float alpha = 1- (fabs(scrollView.contentOffset.y)- 64)/100;
        _headBgBlurView.alpha = alpha;
    }else{
        _headBgBlurView.alpha = 1;
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
}

#pragma mark private
- (void)setNavigationBarTransparent:(NSInteger)isTransparent
{
    [self qb_setTitleText:@""];
    UIImage * img = nil;
    switch (isTransparent) {
        case 0:
        {
            img = IMG2XFROMBUNDLE(@"bg_whitecell1");
        }
            break;
        case 1:
        {
            img = IMGFROMBUNDLE(@"transparent");
            [self.navigationController.navigationBar setBackgroundColor:[UIColor clearColor]];
            self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
        }
            break;
        case 2:
        {
            img = IMG2XFROMBUNDLE(@"bg_qb_topbar01");
            [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
            self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
            [self qb_setTitleText:_vcardEntity.defaultName];
        }
            break;
        default:
            break;
    }
    [self.navigationController.navigationBar setBackgroundImage:img forBarMetrics:UIBarMetricsDefault];
    NSArray* a = self.navigationController.navigationBar.subviews;
    UIView* v = (UIView*)[a firstObject];
    if(isTransparent == 1)
        v.hidden = YES;
    else
        v.hidden = NO;
}


#pragma mark FeedTableViewCellDelegate
- (void)NIMFeedCell:(NIMFeedTableViewCell *)cell actionDidWithFeedEntity:(FeedEntity *)feedEntity actionType:(NIMFeedCellActionType)actionType object:(id)object{
    switch (actionType) {
        case NIMFeedCellActionTypeTypeName:
        {
            //            double userid = feedEntity.userid;
            //            [self showFeedProfileWithuserid:userid animated:YES];
        }
            break;
        case NIMFeedCellActionTypeTypeAvatar:
        {
            //            double userid = feedEntity.userid;
            //            [self showFeedProfileWithuserid:userid animated:YES];
        }
            break;
        case NIMFeedCellActionTypeTypeOption:
        {
            
        }
            break;
        case NIMFeedCellActionTypeTypeImage:
        {
            
        }
            break;
        case NIMFeedCellActionTypeTypeComment:
        {
            UINavigationController *nav = [[UIStoryboard storyboardWithName:@"NIMSquare" bundle:[SSIMBundleTool getBundle]] instantiateViewControllerWithIdentifier:@"doCommentIndifier"];
            
            [self.navigationController presentViewController:nav animated:YES completion:^{
                
            }];
        }
            break;
        case NIMFeedCellActionTypeTypePraise:
        {
            
        }
            break;
        case NIMFeedCellActionTypeTypeTextClick:
        {
            
        }
            break;
        default:
            break;
    }
}

-(void)pushClickTargetNameWithID:(double)targetId{
    
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 0;
}
//
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0)
    {
        return 0;
    }
    return _postDataSourceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

#pragma mark NIMFeedCellDelegate

- (void)feedUserClick:(FeedEntity*)feedEntity{
    //    [self showFeedProfileWithuserid:feedEntity.userid animated:YES];
}
- (void)feedShareClick:(FeedEntity*)feedEntity
{
    
}
- (void)showOrHiddenMoreTextInfo:(FeedEntity*)feedEntity adIndex:(NIMFeedBaseCell *)cell{
    NSString* str = [_cellShowTextDataSource objectForKey:[NSString stringWithFormat:@"%ld",(long)cell.tag]];
    [_cellShowTextDataSource setValue:(str.integerValue == 0?@"1":@"0") forKey:[NSString stringWithFormat:@"%ld",(long)cell.tag]];
    NSIndexPath* indexPath = [NSIndexPath indexPathForItem:cell.tag inSection:1];
    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

- (void)emojiLabelClick:(FeedEntity*)feedEntity clickStr:(NSString*)str withType:(MLEmojiLabelLinkType)type{
    switch (type) {
        case MLEmojiLabelLinkTypeURL:
        {
            
        }
            
            break;
        case MLEmojiLabelLinkTypeEmail:{
            
        }
            break;
        case MLEmojiLabelLinkTypePhoneNumber:{
            NSMutableString * strPhone=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",str];
            if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:strPhone]]){
                NIMRIButtonItem* call = [NIMRIButtonItem itemWithLabel:@"确定" action:^{
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strPhone]];
                }];
                NIMRIButtonItem* cancel = [NIMRIButtonItem itemWithLabel:@"取消" action:^{
                    
                }];
                UIAlertView* alert = [[UIAlertView alloc] initWithNimTitle:@"提醒" message:[NSString stringWithFormat:@"你确定要拨打该电话：%@",str] cancelButtonItem:cancel otherButtonItems:call, nil];
                [alert show];
            }
        }
            break;
        case MLEmojiLabelLinkTypeAt:{
            
        }
            break;
        case MLEmojiLabelLinkTypePoundSign:{
            
        }
            break;
            
        default:
            break;
    }
}

#define kHeightHeader 40
- (NSDateComponents *)dateComponentsWithDate:(NSDate *)date{
    NSCalendar *cal = [NSCalendar currentCalendar];
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dd = [cal components:unitFlags fromDate:date];
    return dd;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //    NSString* tmpStr = [_cellShowTextDataSource objectForKey:[NSString stringWithFormat:@"%d",indexPath.row]];
    //    BOOL tmp = (tmpStr.integerValue==0?NO:YES);
    if(indexPath.section == 0)
    {
        if(indexPath.row == 0){
            if(_firendsNum.integerValue == 0)
                return 0;
            else
                return 80;
        }
        float viewH = [UIScreen mainScreen].bounds.size.height;
        float sectionH = 15;
        
        if(indexPath.row == 1){
            if(_totalCount.integerValue == 0 && _gamesCount.integerValue == 0)return 0;
            else{
                return (250.0/1334.0)*viewH + sectionH;
            }
        }
    }
    //    PostsModel *model = [_postDataSourceArray objectAtIndex:indexPath.row];
    //    float cellH = [QBCommunityCell getCellHeight:model];
    //    if (indexPath.row == 0) {
    //        cellH = cellH + 28;
    //    }
    return 50;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 0)
    {
        
        
        return;
    }
    
    //    PostsModel *postModel = (PostsModel *)[_postDataSourceArray objectAtIndex:indexPath.row];
    //    NSString *postUrl = postModel.posturl ;
    //    QBCommunityWebViewCtroller *cmt = [[QBCommunityWebViewCtroller alloc]init];
    //    [cmt setWebTitle:@"叮铃社区" url:[NSURL URLWithString:postUrl]];
    //    [_navigationController pushViewController:cmt animated:YES];
    
    DBLog(@"selected index : %lu",(long)indexPath.row);
}

#pragma mark NSFetchedResultsControllerDelegate
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
    if(controller == _fetchedResultsControllerForVcard){
        
        //[self configFriendshipBtn];
        return;
    }
}

- (void)rightButtonAction:(id)sender{
    
}

- (void)fetchUserHomepage{}


#pragma mark fetch
- (NSFetchedResultsController *)fetchedResultsController{
    if (!_fetchedResultsController) {}
    return _fetchedResultsController;
}

- (NSFetchedResultsController*)fetchedResultsControllerForVcard{
    if (!_fetchedResultsControllerForVcard) {
        //        _fetchedResultsControllerForVcard = [VcardEntity QB_fetchAllGroupedBy:nil
        //                                                       withPredicate:nil
        //                                                            sortedBy:nil
        //                                                           ascending:NO
        //                                                            delegate:self];
        if ([_fetchedResultsControllerForVcard performFetch:nil]) {
        }
    }
    return _fetchedResultsControllerForVcard;
}

- (void)showFeedProfileWithuserid:(int64_t)userid animated:(BOOL)animated{
    
    //    if((userid <= 0) || ([[NIMManager sharedImManager] owerid] == userid) || (userid == _vcardEntity.userid))
    //    {
    //        return;
    //    }
    NIMFeedProfileViewController *feedProfileVC = [[UIStoryboard storyboardWithName:@"NIMSquare" bundle:[SSIMBundleTool getBundle]] instantiateViewControllerWithIdentifier:@"NIMFeedProfileViewController"];
    feedProfileVC.userid = userid;
    [feedProfileVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:feedProfileVC animated:animated];
}


- (UIButton*)optionBtn{
    if(!_optionBtn){
        _optionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        CGRect rect = [UIApplication sharedApplication].keyWindow.bounds;
        //        _optionBtn.frame = CGRectMake(0, rect.size.height-59, rect.size.width, 59);
        _optionBtn.backgroundColor = [UIColor redColor];
        [_optionBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_optionBtn addTarget:self action:@selector(friendBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        //        [[UIApplication sharedApplication].keyWindow addSubview:_optionBtn];
        [self.view addSubview:_optionBtn];
        if (_optionBtn.superview !=nil) {
            [_optionBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.leading.offset(0);
                make.trailing.offset(0);
                make.bottom.offset(0);
                make.height.offset(59);
            }];
            
        }
        
    }
    
    return _optionBtn;
}





- (UIView*)optionBtnLine{
    if(!_optionBtnLine){
        _optionBtnLine = [[UIView alloc] init];
        [_optionBtn addSubview:_optionBtnLine];
        [_optionBtnLine mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.offset(0);
            make.trailing.offset(0);
            make.top.offset(0);
            make.height.offset(_LINE_HEIGHT_1_PPI);
        }];
    }
    return _optionBtnLine;
}

- (NSMutableArray*)goodsList{
    if(!_goodsList){
        _goodsList = [[NSMutableArray alloc] init];
    }
    return _goodsList;
}
- (NSMutableArray*)gamesList{
    if(!_gamesList){
        _gamesList = [[NSMutableArray alloc] init];
    }
    return _gamesList;
}
- (NSMutableDictionary*)cellShowTextDataSource{
    if(!_cellShowTextDataSource){
        _cellShowTextDataSource = [[NSMutableDictionary alloc] init];
    }
    return _cellShowTextDataSource;
}


- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}


- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(_tableView.contentOffset.y>64){
        [self setNavigationBarTransparent:2];
    }else{
        [self setNavigationBarTransparent:1];
    }
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    //DBLog(@"------------ %@",_headerView.constraints);
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self setNavigationBarTransparent:0];
    [self preferredStatusBarStyle];
    _userDataBack = YES;
    [self qb_setNavStyleTheme:THEME_COLOR_WHITHE];
    [self qb_setStatusBar_Default];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self setNavigationBarTransparent:0];
    //_optionBtn.hidden = YES;
    _userDataBack = YES;
    [self qb_setNavStyleTheme:THEME_COLOR_WHITHE];
    [self qb_setStatusBar_Default];
}

- (void)qb_back{
    _userDataBack = YES;
    [self setNavigationBarTransparent:2];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    _tableView.delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



//-(NSMutableAttributedString *)stringWithString:(NSString *)astring withSex:(NSString *)sex{
//    if(!astring)
//        return nil;
//
//    astring =[NSString stringWithFormat:@"%@[%@]",astring,IsStrEmpty(sex)?@"F":sex];
//    NSMutableAttributedString *rString = [[NSMutableAttributedString alloc ] initWithString:astring attributes:nil ] ;
//    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
//    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
//    paragraphStyle.alignment = NSTextAlignmentCenter;
//    paragraphStyle.minimumLineHeight = 18.f;
//    paragraphStyle.maximumLineHeight = 18.f;
//
//    [rString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:NSMakeRange(0, astring.length)];
//    [rString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, astring.length)];
//
//
//
//    NSString *source = [SSIMSpUtil trimString:astring];
//    NSRegularExpression * regular   = [[NSRegularExpression alloc]initWithPattern:@"\\[[^\\[\\]\\s]+\\]" options:NSRegularExpressionDotMatchesLineSeparators|NSRegularExpressionCaseInsensitive error:nil];
//    NSArray             * array     = [regular matchesInString:source options:0 range:NSMakeRange(0, [source length])];
//    int count = [array count];
//    int offset = 0;
//    for(int i = 0 ; i < count ; i++)
//    {
//        NSTextCheckingResult * result   = [array objectAtIndex:i];
//        NSString             * string   = [source substringWithRange:result.range];
//        NSMutableString * iconStr= nil;
//        if([string isEqualToString:@"[F]"])
//        {
//            iconStr=[NSMutableString stringWithFormat:@"icon_girl.png"];
//        }
//        else if([string isEqualToString:@"[M]"])
//        {
//            iconStr=[NSMutableString stringWithFormat:@"icon_boy.png"];
//        }
//
//        NIMTextAttachment * textAttachment = [[NIMTextAttachment alloc ] initWithData:nil ofType:nil ] ;
//        UIImage * smileImage = IMGFROMBUNDLE(iconStr);
//        textAttachment.image = smileImage;
//        textAttachment.bounds = CGRectMake(0, 0, 11, 11);
//        NSRange range = result.range;
//        range = NSMakeRange(range.location - offset, range.length);
//        NSAttributedString * textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];
//
//        [rString replaceCharactersInRange:range withAttributedString:textAttachmentString];
//        offset += range.length -1;
//
//    }
//
//    return rString;
//}





_GETTER_BEGIN(NIMTNoDataView, qbm_viewNoData)
{
    _qbm_viewNoData = _ALLOC_OBJ_(NIMTNoDataView);
    _qbm_viewNoData.delegate = self;
}
_GETTER_END(qbm_viewNoData)

_GETTER_BEGIN(UIImageView, mySexImg)
_mySexImg = [[UIImageView alloc] init];
_GETTER_END(mySexImg)




@end
